# Copyright (c) 2024-present AI-Labs

import requests
import base64
import os

"""
获取文件保存到本地
"""
def fetch_file(source, output_filename):
    if source.startswith('http://') or source.startswith('https://'):
        # 从URL获取音频文件
        response = requests.get(source)
        response.raise_for_status()  # 确保请求成功
        with open(output_filename, 'wb') as f:
            f.write(response.content)

    elif source.startswith('data:'):
        # 从Base64字符串获取音频文件
        # 移除Base64字符串可能存在的前缀
        base64_str = source.split(',')[1] if source.startswith('data:') else source
        # 移除Base64字符串中的换行符
        base64_str = base64_str.replace('\n', '').replace('\r', '')
        # Base64解码
        content = base64.b64decode(base64_str)
        # 将解码后的数据写入到音频文件
        with open(output_filename, 'wb') as f:
            f.write(content)
